#include "stdafx.h"
#include "GraphicHolder.h"
#include <lambda/lambda.hpp>
#include <lambda/bind.hpp>
#include <lambda/construct.hpp>
using namespace boost::lambda;
namespace Graphics
{
	GraphicHolder::GraphicHolder(std::pair<API_TYPE,Window> param)
		:m_Graphic2D(0),m_API(API_UNDEF)
	{
		API_TYPE api=param.first;
		Window& win=param.second;


		m_API = api;


		if(api == API_D3D9)
		{
			m_Graphic2D = new D3Ds::GraphicD3D(win);
		}
		else
		{
			m_API = API_UNDEF;
			m_Graphic2D = 0;
			throw(std::exception("hello , what's a pity, we have no opengl yet"));
		}


	}

	GraphicHolder::~GraphicHolder(void)
	{
		for(stdext::hash_map<string,Drawable*>::iterator i=m_Cache.begin();i!=m_Cache.end();i++)
		{
			if(i->second )
			{
				delete i->second;
				i->second = 0;
			}
		}
		if(m_Graphic2D != 0)
		{
			delete m_Graphic2D;
		}
	}

	API_TYPE& GraphicHolder::GetAPI(void)
	{
		return m_API;
	}

	Graphic2D* const GraphicHolder::GetGraphic2D(void)
	{
		if(m_Graphic2D != 0)
		{
			return m_Graphic2D;
		}
		else
		{
			throw(std::exception("Graphic2D uninitialize"));
		}
	}

	Drawable* GraphicHolder::CreateDrawable(int width, int height)
	{
		Drawable* dd = 0;
		try
		{
			if(m_API == API_D3D9)
			{
				dd = new D3Ds::DrawableD3D(width,height);
			}
		}
		catch(...)
		{
			return 0;
		}
		return dd;
	}
	Drawable* GraphicHolder::GetDrawableFromCache(const std::string& filename,DWORD colorKey)
	{
		std::string key =filename;
		char str[10];
		str[0] = '|';
		_itoa_s((int)colorKey,str+1,9,16);
		key.append(str);
		
		Drawable* dd = m_Cache[key];

		if( dd == 0)
		{
			try
			{
				dd = new D3Ds::DrawableD3D(filename,colorKey);
				m_Cache[key] = dd;
			}
			catch(...)
			{
				dd = 0;
			}
		}

		return dd;
	}
	Drawable* GraphicHolder::CreateDrawable(const std::string& filename,DWORD colorKey)
	{
		Drawable* dd = 0;
		try
		{
			if(m_API == API_D3D9)
			{
				dd = new D3Ds::DrawableD3D(filename,colorKey);
			}
		}
		catch(...)
		{
			return 0;
		}
		return dd;
	}
}